import React, { useContext, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { UserInfo, ApiResponse } from "../types/user";
import { InitialStateContext } from "../context/InitialStateContext";
import "./UserInfo.css";

const UserInfoPage: React.FC = () => {
  const initialState = useContext(InitialStateContext);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(
    initialState?.userInfo || null
  );
  const [loading, setLoading] = useState(!userInfo);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!userInfo) {
      fetch("/api/getUserInfo")
        .then((res) => res.json())
        .then((res: ApiResponse<UserInfo>) => {
          if (res.code === 0) {
            setUserInfo(res.data);
          } else {
            setError(res.message);
          }
        })
        .catch((err) => {
          setError(err.message);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [userInfo]);

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error) {
    return <div>错误：{error}</div>;
  }

  if (!userInfo) {
    return <div>未找到用户信息</div>;
  }

  return (
    <div className="user-info-container">
      <h1 className="user-info-title">用户详情</h1>
      <div>
        <p className="user-info-item">姓名：{userInfo.name}</p>
        <p className="user-info-item">年龄：{userInfo.age}</p>
        <p className="user-info-item">
          性别：{userInfo.gender === "male" ? "男" : "女"}
        </p>
        <p className="user-info-item">手机：{userInfo.phone}</p>
        <p className="user-info-item">
          地址：{userInfo.address.province}
          {userInfo.address.city}
          {userInfo.address.detail}
        </p>
      </div>
      <Link to="/" className="user-info-back">
        返回首页
      </Link>
    </div>
  );
};

export default UserInfoPage;
